package org.spring.boot.fusion.mapper;
import java.util.Properties;
import org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.interceptor.TransactionInterceptor;

/**
 * @Description: 统一管理事务
 * @author: 赵兴炎
 * @date: 2019年7月9日
 */
@Configuration
public class FusionTransactionManagerConfig {

	private final String PROPAGATION_NAME_CHANGE = "PROPAGATION_REQUIRED,-Exception";
	private final String PROPAGATION_NAME_SELECT = "PROPAGATION_REQUIRED,-Exception,readOnly";

	@Autowired
	private DataSourceTransactionManager transactionManager;

	@Bean(name = "transactionManagerAdvice")
	public TransactionInterceptor transactionInterceptor() throws Exception {
		Properties properties = new Properties();
		properties.setProperty("add*", PROPAGATION_NAME_CHANGE);
		properties.setProperty("save*", PROPAGATION_NAME_CHANGE);
		properties.setProperty("insert*", PROPAGATION_NAME_CHANGE);
		properties.setProperty("update*", PROPAGATION_NAME_CHANGE);
		properties.setProperty("delete*", PROPAGATION_NAME_CHANGE);
		properties.setProperty("get*", PROPAGATION_NAME_SELECT);
		properties.setProperty("find*", PROPAGATION_NAME_SELECT);
		return new TransactionInterceptor(transactionManager, properties);
	}

	@Bean
	public BeanNameAutoProxyCreator beanNameAutoProxyCreator() {
		BeanNameAutoProxyCreator beanNameAutoProxyCreator = new BeanNameAutoProxyCreator();
		beanNameAutoProxyCreator.setInterceptorNames("transactionManagerAdvice");
		beanNameAutoProxyCreator.setBeanNames("*Service", "*ServiceImpl");
		beanNameAutoProxyCreator.setProxyTargetClass(true);
		return beanNameAutoProxyCreator;
	}
}